<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\model;

use app\admin\controller\Staff;
use app\admin\model\AdminUser;
use app\admin\model\Config;
use app\api\model\Token;
use app\common\controller\Adminbase;
use think\Controller;
use think\Exception;
use think\facade\Validate;
use think\Model;


class StaffModel extends Model
{
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;

    protected $table = 'yzn_staff';

    protected $rule = '\app\admin\validate\Staff';

    public function user()
    {
        return $this->belongsTo(DouyinModel::class, 'uid', 'id')->setEagerlyType(0);
    }

    public function admin()
    {
        return $this->belongsTo(AdminUser::class, 'aid', 'id', [], 'LEFT');
    }

    //登陆
    public function login($param)
    {

        try {
            if (!$param['phone'] || !$param['password']) {
                throw new Exception("缺少参数");
            }
            $username = trim($param['phone']);
            $password = trim($param['password']);
            $user = self::get(['phone' => $username]);
            if (!$user) {
                throw new Exception('用户名不存在');
            }
            if ($user->password != encrypt_password($password, $user->encrypt)) {
                throw new Exception('密码不正确');
            }

            if ($user->status == 0) {
                throw new Exception('账号已被封禁，请联系管理员');
            }

            $wxUserMes['token'] = (new Token())->product_token($user['id'], 1);
            $wxUserMes['uid'] = $user->id;
            return ['code' => 200, 'msg' => '获取信息成功', 'data' => $wxUserMes];

        } catch (Exception $e) {
            return ['code' => 201, 'msg' => $e->getMessage()];
        }
    }


    //注册
    public function register($params = array())
    {
        try {
            $validate = new $this->rule;
            $params['password1'] = $params['password'];
            if (!$validate->scene('register')->check($params)) {
                // 验证失败，返回错误信息
                throw new Exception($validate->getError());
            }


            //验证激活码
            $code = (new Config())->where(['name' => 'code'])->value('value');
            if ($code != $params['code']) {
                throw new Exception('激活码不正确');
            }

            $passwordinfo = encrypt_password($params['password1']); //对密码进行处理
            $params['password'] = $passwordinfo['password'];
            $params['encrypt'] = $passwordinfo['encrypt'];
            $model = new self();
            if(isset($params['aid']) && $params['aid']){
                $model->aid = $params['aid'];
            }
            $model->phone = $params['phone'];
            $model->password = $params['password'];
            $model->encrypt = $params['encrypt'];
            $model->username = $params['username'];


            if (!$model->save()) {
                throw new Exception('注册失败，请重新尝试');
            }
            $ApplyTeamModel = (new ApplyTeamModel());
            //添加申请团队
            $ApplyTeamModel->uid =  $model->id;
            $ApplyTeamModel->aid = $params['team_id'];
            $ApplyTeamModel->status = 0;
            $ApplyTeamModel->no_reason = NULL;
            $ApplyTeamModel->add_reason = "注册申请团队";
            $ApplyTeamModel->save();

            return ['code' => 200, 'msg' => '团队申请成功，等待审核'];

        } catch (Exception $e) {
            return ['code' => 201, 'msg' => $e->getMessage()];
        }
    }


    public function getUser($params = array())
    {
        $user = self::where(['id' => $params['uid']])->field('id,username,avatar,phone,aid,is_head')->find();
        if (!$user) {
            return ['code' => 201, 'msg' => '用户不存在'];
        }
        //获取用户加入团队状态
        $user['apply_team_status'] = true;
        if(!$user['aid']){
            //查询是否有申请记录
            $count = (new ApplyTeamModel())->where(['uid' =>$params['uid']])->count();
            if($count == 0){
                $user['apply_team_status'] = false;
            }
        }
        //获取团队名称
        $user['team_name'] = (new AdminUser())->where(['id' => $user['aid']])->value('team_name');
        return ['code' => 200, 'msg' => '获取成功', 'data' => $user];
    }

    public function updateUser($params = array()){
         $user = self::get($params['uid']);
         if(!$user){
             return ['code' => 201, 'msg' => '用户不存在'];
         }

         $user->username = $params['username'];
         $user->avatar = $params['avatar'];

         if($user->save()){
             return ['code' => 200, 'msg' => '修改成功', 'data' =>[]];
         }
        return ['code' => 201, 'msg' => '修改失败'];
    }


    public function updatePassword($param)
    {
        try {
            $oldPassword = trim($param['oldPassword']);
            $staff = self::where(['id' => $param['uid']])->find();
            if (!$staff) {
                throw new Exception("用户不存在");
            }

            if ($staff->password != encrypt_password($oldPassword, $staff->encrypt)) {
                throw new Exception("原始密码不正确");
            }

            if (trim($param['newPassword']) != trim($param['password_confirm'])) {
                throw new Exception("两次密码输入不一致");
            }

            $passwordinfo = encrypt_password(trim($param['newPassword'])); //对密码进行处理
            $params['password'] = $passwordinfo['password'];
            $params['encrypt'] = $passwordinfo['encrypt'];

            if (!$staff->save($params)) {
                throw new Exception("修改失败请重新尝试");
            }
            return ['code' => 200, 'msg' => '修改成功', 'data' => []];
        } catch (\Exception $e) {
            return ['code' => 201, 'msg' => $e->getMessage()];
        }
    }


    public function loginOut($parma){
        $token = \think\Db::name('user_token')->where(['user_id' => $parma['uid']])->delete();
        if($token){
            return ['code'=>200,'msg'=>'退出成功','data' => []];
        }
        return ['code' => 201, 'msg' =>'退出失败'];
    }


    public function forgotPwd($params){
         //验证验证码
        $result = \app\common\library\Sms::check($params['phone'], $params['code']);
        if(!$result){
            return ['code' => 201, 'msg' =>'验证码错误'];
        }

        if(!$params['password']){
            return ['code' => 201, 'msg' =>'请填写密码'];
        }
        $passwordinfo = encrypt_password(trim($params['password'])); //对密码进行处理
        $data['password'] = $passwordinfo['password'];
        $data['encrypt'] = $passwordinfo['encrypt'];

        //更新代码
        if(!self::where(['phone' => $params['phone']])->update($data)){
            return ['code' => 201, 'msg' =>'更改失败'];
        }
        return ['code' => 200, 'msg' =>'更新成功'];
    }

}
